<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            filterable
            @change="gainCommunityId"
        >
          <el-option v-for="c in community" :label=" c.name || c.communityId" :value="c.communityId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼宇" prop="buildingId">
        <el-select
            v-model="queryParams.buildingId"
            placeholder="请选择楼宇"
            clearable
            filterable
        >
          <el-option v-for="b in building" :label="b.name || b.buildingName || b.buildingId" :value="b.buildingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单元号" prop="unitNo">
        <el-input
            v-model="queryParams.unitNo"
            placeholder="请输入单元号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间号" prop="roomNo">
        <el-input
            v-model="queryParams.roomNo"
            placeholder="请输入房间号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼层号" prop="floorNo">
        <el-input
            v-model="queryParams.floorNo"
            placeholder="请输入楼层号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑面积" prop="buildingArea">
        <el-input
            v-model="queryParams.buildingArea"
            placeholder="请输入建筑面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用面积" prop="usableArea">
        <el-input
            v-model="queryParams.usableArea"
            placeholder="请输入使用面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公摊面积" prop="publicArea">
        <el-input
            v-model="queryParams.publicArea"
            placeholder="请输入公摊面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关连储藏室房间号" prop="storageRoomNo">
        <el-input
            v-model="queryParams.storageRoomNo"
            placeholder="请输入关连储藏室房间号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联车位号" prop="parkingNo">
        <el-input
            v-model="queryParams.parkingNo"
            placeholder="请输入关联车位号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房屋朝向" prop="orientation">
        <el-input
            v-model="queryParams.orientation"
            placeholder="请输入房屋朝向"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间编号" prop="roomNumber">
        <el-input
            v-model="queryParams.roomNumber"
            placeholder="请输入房间编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['comsys:house:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['comsys:house:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['comsys:house:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['comsys:house:export']"
        >导出
        </el-button>
      </el-col>
      <!-- 在现有按钮区域添加导入按钮 -->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['comsys:house:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="房屋ID" align="center" prop="houseId"/>
      <el-table-column label="社区" align="center" prop="communityId">
        <template #default="scope">
          <span>{{ getCommunityName(scope.row.communityId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼宇" align="center" prop="buildingId">
        <template #default="scope">
          <span>{{ getBuildingName(scope.row.buildingId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单元号" align="center" prop="unitNo"/>
      <el-table-column label="房间号" align="center" prop="roomNo"/>
      <el-table-column label="楼层号" align="center" prop="floorNo"/>
      <el-table-column label="建筑面积" align="center" prop="buildingArea">
        <template #default="scope">
          <span>{{ scope.row.buildingArea ? scope.row.buildingArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用面积" align="center" prop="usableArea">
        <template #default="scope">
          <span>{{ scope.row.usableArea ? scope.row.usableArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房屋类型" align="center" prop="houseType"/>
      <el-table-column label="房屋状态" align="center" prop="houseStatus"/>
      <el-table-column label="房间类型(X室X厅X卫)" align="center" prop="roomType"/>
      <el-table-column label="公摊面积" align="center" prop="publicArea">
        <template #default="scope">
          <span>{{ scope.row.publicArea ? scope.row.publicArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联车位号" align="center" prop="parkingNo"/>
      <el-table-column label="房屋朝向" align="center" prop="orientation"/>
      <el-table-column label="房间编号" align="center" prop="roomNumber"/>
      <el-table-column label="房屋图片" align="center" prop="images">
        <template #default="scope">
          <div v-if="scope.row.images" class="table-image-container">
            <el-image
                :src="scope.row.images"
                :preview-src-list="[scope.row.images]"
                class="table-preview-item"
                fit="cover"
                lazy
            />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="修改时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ scope.row.updateTime || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="User" @click="handleBindOwner(scope.row)"
                     v-hasPermi="['comsys:house:edit']">绑定业主
          </el-button>
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['comsys:house:query']">
            查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['comsys:house:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['comsys:house:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改房屋管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="houseRef" :model="form" :rules="rules" label-width="80px">
        <!-- 社区下拉框 -->
        <el-form-item label="社区">
          <el-select v-model="form.communityId" placeholder="请选择社区" clearable @change="gainCommunityId">
            <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId"></el-option>
          </el-select>
        </el-form-item>

        <!-- 楼宇下拉框 -->
        <el-form-item label="楼宇">
          <el-select v-model="form.buildingId" placeholder="请选择楼宇">
            <el-option v-for="b in building" :label="b.name || b.buildingName || b.buildingId" :value="String(b.buildingId)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元号" prop="unitNo">
          <el-input v-model="form.unitNo" placeholder="请输入单元号"/>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo">
          <el-input v-model="form.roomNo" placeholder="请输入房间号"/>
        </el-form-item>
        <el-form-item label="楼层号" prop="floorNo">
          <el-input v-model="form.floorNo" placeholder="请输入楼层号"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积"/>
        </el-form-item>
        <el-form-item label="使用面积" prop="usableArea">
          <el-input v-model="form.usableArea" placeholder="请输入使用面积"/>
        </el-form-item>
        <el-form-item label="公摊面积" prop="publicArea">
          <el-input v-model="form.publicArea" placeholder="请输入公摊面积"/>
        </el-form-item>
        <el-form-item label="关连储藏室房间号" prop="storageRoomNo">
          <el-input v-model="form.storageRoomNo" placeholder="请输入关连储藏室房间号"/>
        </el-form-item>
        <el-form-item label="关联车位号" prop="parkingNo">
          <el-input v-model="form.parkingNo" placeholder="请输入关联车位号"/>
        </el-form-item>
        <el-form-item label="房屋朝向" prop="orientation">
          <el-input v-model="form.orientation" placeholder="请输入房屋朝向"/>
        </el-form-item>
        <el-form-item label="房间编号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间编号"/>
        </el-form-item>
        <el-form-item label="图片(JSON数组)" prop="images">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
          >
            <img v-if="form.images" :src="form.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="房屋状态" prop="houseStatus">
          <el-select v-model="form.houseStatus" placeholder="请选择或输入房屋状态" filterable allow-create clearable>
            <el-option label="有效" value="有效"/>
            <el-option label="空置" value="空置"/>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <div style="text-align: center; padding: 20px 0;">
        <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            :file-list="fileList"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" class="link-type" @click="handleTemplate">下载模板</el-link>
            </div>
          </template>
        </el-upload>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定业主弹窗组件 -->
    <el-dialog v-model="bindOwnerOpen" title="绑定业主" width="520px">
      <el-form :model="bindForm" label-width="88px">
        <el-form-item label="房屋ID">
          <span>{{ bindForm.houseId }}</span>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="bindForm.ownerName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="bindForm.ownerMobile" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindOwnerOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitBindOwner">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗组件 -->
    <el-dialog v-model="viewOpen" title="房屋详情" width="640px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="房屋ID">{{ viewInfo.houseId }}</el-descriptions-item>
        <el-descriptions-item label="房间号">{{ viewInfo.roomNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="建筑面积">{{ viewInfo.buildingArea || '-' }}</el-descriptions-item>
        <el-descriptions-item label="使用面积">{{ viewInfo.usableArea || '-' }}</el-descriptions-item>
        <el-descriptions-item label="房间类型">{{ viewInfo.roomType || '-' }}</el-descriptions-item>
        <el-descriptions-item label="朝向">{{ viewInfo.orientation || '-' }}</el-descriptions-item>
        <el-descriptions-item label="房间编号">{{ viewInfo.roomNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ viewInfo.status || '-' }}</el-descriptions-item>
        <el-descriptions-item label="楼宇">{{ getBuildingName(viewInfo.buildingId) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" @click="viewOpen = false">关 闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="House">
import {listHouse, getHouse, delHouse, addHouse, updateHouse} from "@/api/comsys/house"
import {getToken} from "@/utils/auth.js";
import {importBuilding} from "@/api/comsys/mange.js";
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import request from "@/utils/request.js";

const {proxy} = getCurrentInstance()
const router = useRouter()

const houseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    buildingId: null,
    unitNo: null,
    roomNo: null,
    floorNo: null,
    buildingArea: null,
    usableArea: null,
    houseType: null,
    houseStatus: null,
    roomType: null,
    publicArea: null,
    storageRoomNo: null,
    parkingNo: null,
    orientation: null,
    roomNumber: null,
    images: null,
    description: null,
  },
  rules: {}
})

const {queryParams, form, rules} = toRefs(data)

/** 查询房屋管理列表 */
function getList() {
  loading.value = true
  listHouse(queryParams.value).then(response => {
    houseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    houseId: null,
    communityId: null,
    buildingId: null,
    unitNo: null,
    roomNo: null,
    floorNo: null,
    buildingArea: null,
    usableArea: null,
    houseType: null,
    houseStatus: null,
    roomType: null,
    publicArea: null,
    storageRoomNo: null,
    parkingNo: null,
    orientation: null,
    roomNumber: null,
    images: null,
    description: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("houseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.houseId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 若查询区已选社区，则默认带入并加载楼宇选项
  if (queryParams.value?.communityId) {
    form.value.communityId = queryParams.value.communityId
    gainCommunityId(form.value.communityId)
  } else {
    building.value = []
    form.value.buildingId = null
  }
  open.value = true
  title.value = "添加房屋管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _houseId = row.houseId || ids.value
  getHouse(_houseId).then(response => {
    form.value = response.data
    // 确保 v-model 与选项值类型一致
    if (form.value?.buildingId != null) {
      form.value.buildingId = String(form.value.buildingId)
    }
    // 加载对应社区的楼宇选项，编辑场景不清空原值，确保默认选中
    if (form.value?.communityId) {
      const originalId = form.value.buildingId
      gainCommunityId(form.value.communityId, { keepFormBuilding: true, keepQueryBuilding: true })
        .then(() => {
          // 选项加载后再强制一次赋值以确保选中
          form.value.buildingId = originalId
        })
    } else {
      building.value = []
      form.value.buildingId = null
    }
    open.value = true
    title.value = "修改房屋管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["houseRef"].validate(valid => {
    if (valid) {
      if (form.value.houseId != null) {
        updateHouse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addHouse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _houseIds = row.houseId || ids.value
  proxy.$modal.confirm('是否确认删除房屋管理编号为"' + _houseIds + '"的数据项？').then(function () {
    return delHouse(_houseIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comsys/house/export', {
    ...queryParams.value
  }, `house_${new Date().getTime()}.xlsx`)
}

/** 绑定业主跳转 */
// 已移除绑定业主与查看详情跳转方法


/** 导入按钮操作 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false
});

const fileList = ref([]);
const uploadRef = ref(null);

// 导入按钮操作
function handleImport() {
  router.push({path: '/comsys/house/import'})
}

// 文件上传相关函数
function handleExceed() {
  proxy.$modal.msgError("只能上传一个文件");
}

function handleFileChange(file, fileList) {
  this.fileList = fileList;
}

// 下载模板
function handleTemplate() {
  proxy.download("comsys/building/importTemplate", {}, `building_template.xlsx`);
}

// 提交上传文件
function submitFileForm() {
  if (fileList.value.length === 0) {
    proxy.$modal.msgError("请选择上传文件");
    return;
  }

  upload.isUploading = true;

  // 创建 FormData 对象
  const formData = new FormData();
  formData.append("file", fileList.value[0].raw);

  // 调用导入 API
  importBuilding(formData)
      .then(response => {
        upload.open = false;
        proxy.$modal.msgSuccess(response.msg);
        getList();
      })
      .catch(err => {
        console.error(err);
        proxy.$modal.msgError("导入失败");
      })
      .finally(() => {
        upload.isUploading = false;
      });
}

const headers = ref({Authorization: "Bearer " + getToken()})
// 图片上传
const handleAvatarSuccess = (
    response
) => {
  ElMessage.success("上传成功")
  form.value.images = response.msg
  // console.log(response)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//添加房屋信息
//社区下拉框绑定
const community = ref([]);
const building = ref([])
const initCommunity = () => {
  request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data;
  })
}

//根据社区联动楼宇
//获取当前选中的社区ID
const gainCommunityId = (cid, options = {}) => {
  console.log('选中的社区ID:', cid);
  const { keepFormBuilding = false, keepQueryBuilding = false } = options

  // 根据场景决定是否清空楼宇选择
  if (!keepFormBuilding) {
    form.value.buildingId = null
  }
  if (!keepQueryBuilding && queryParams.value) {
    queryParams.value.buildingId = null
  }
  building.value = []

  if (cid) {
    return request({
      url: `/building/getBuildingVoNameAndId/${cid}`,
      method: 'get'
    }).then((response) => {
      building.value = response.data
    })
  }
  return Promise.resolve()
}

// 绑定业主与查看详情状态与方法
const bindOwnerOpen = ref(false)
const viewOpen = ref(false)
const currentHouse = ref(null)
const bindForm = reactive({
  houseId: null,
  ownerName: '',
  ownerMobile: ''
})
const viewInfo = ref({})

function handleBindOwner(row) {
  currentHouse.value = row
  bindForm.houseId = row.houseId
  bindForm.ownerName = ''
  bindForm.ownerMobile = ''
  bindOwnerOpen.value = true
}

function submitBindOwner() {
  proxy.$modal.msgSuccess('绑定业主信息已提交')
  bindOwnerOpen.value = false
}

function handleView(row) {
  currentHouse.value = row
  viewOpen.value = true
  getHouse(row.houseId).then(res => {
    viewInfo.value = res.data || {}
  })
}

// 名称映射（社区/楼宇）
const getCommunityName = (id) => {
  const list = Array.isArray(community.value) ? community.value : []
  const item = list.find(c => String(c.communityId) === String(id))
  return item ? (item.name ?? item.communityId) : id
}

// 预加载所有社区的楼宇名称，构建全局映射，保证表格刷新时也能显示名称
const buildingMap = ref({})
async function preloadAllBuildings() {
  const list = Array.isArray(community.value) ? community.value : []
  if (!list.length) return
  try {
    const responses = await Promise.all(
      list.map(c => request({ url: `/building/getBuildingVoNameAndId/${c.communityId}`, method: 'get' }))
    )
    const map = {}
    responses.forEach(res => {
      const arr = res?.data || []
      arr.forEach(b => {
        map[String(b.buildingId)] = b.name || b.buildingName || b.buildingId
      })
    })
    buildingMap.value = map
  } catch (e) {
    // 忽略预加载失败，保持回退逻辑
  }
}

const getBuildingName = (id) => {
  const key = String(id)
  const mapName = buildingMap.value && buildingMap.value[key]
  if (mapName) return mapName
  const list = Array.isArray(building.value) ? building.value : []
  const item = list.find(b => String(b.buildingId) === key)
  return item ? (item.name ?? item.buildingName ?? item.buildingId) : id
}

// 社区列表变化后预加载楼宇映射
watch(community, (val) => {
  if (Array.isArray(val) && val.length) preloadAllBuildings()
})

initCommunity()
if (queryParams?.value?.communityId) {
  gainCommunityId(queryParams.value.communityId)
}
getList()
</script>

<style scoped>
/* 作用于整个表单 */
:deep(.el-form) {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2px 30px;
  grid-auto-flow: dense; /* 支持跨列元素 */
}

/* 让 textarea、图片上传等宽元素占满两列 */
:deep(.el-form-item--large),
:deep(.el-form-item[label='详细地址']),
:deep(.el-form-item[label='社区描述']),
:deep(.el-form-item[label='图片(JSON数组)']),
:deep(.el-form-item[label='经纬度']) {
  grid-column: span 2;
}

/* 可选：调整 label 宽度适应新布局 */
:deep(.el-form-item__label) {
  width: 108px !important;
}
</style>

<style scoped>
.avatar-uploader, .avatar-uploader.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover { border-color: var(--el-color-primary); }
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}
</style>
